/*
 * @Author: Otway
 * @Date: 2019-01-09 11:16:08
 * @LastEditors: Otway
 * @LastEditTime: 2019-08-30 18:50:09
 * @copyright: h-visions
 */
import React, { PureComponent } from 'react';
import {
  Row,
  Col,
  Form,
  Input,
  DatePicker,
  Upload,
  Button,
  Icon,
  Menu,
  Layout,
  Divider,
  Spin, Modal
} from 'antd';
import DetailsForm from './DetailsForm'
import * as FileService from '../../../axios/File'
import * as SpecialMachineService from '../../../axios/SpecialMachine'
import { openModalMessage } from '../../../components/TableCustomize';
import FileViewer from 'react-file-viewer';

const FormItem = Form.Item;
const { SubMenu } = Menu;
const { Content, Sider } = Layout;
const formItemLayout = {
  // 抽屉里面Form。二列的布局比例
  labelCol: {
    span: 6
  },
  wrapperCol: {
    span: 18
  }
};

class Details extends PureComponent {
  state = {
    spinning: false,
    current: '安排表',
    fileList: [],
    menuList: [],
    formData: {},
    batchNoOld: [],
    batchNoNew: [],
    printArr: [],
    pictureSrc: '',
	fileSrc: '',
    pictureVisible: false,
	fileVisible: false,
  }
  componentDidMount() {
    const { formData } = this.props;
    this.setState({ formData, batchNoOld: [formData] }, this.getFileList);
	 }
  handleClick = e => {
    console.log('click ', e);
    const { menuList } = this.state;
    let printArr = []
    if (e.key !== '安排表') {
      for (var item of menuList) {
        if (item.id === e.key) {
          printArr.push(item)
        }
      }
    }
    this.setState({
      current: e.key,
      printArr
    });
  };
 static mimeTypeMap = {
  '.pdf': 'application/pdf',
  '.doc': 'application/msword',
  '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  '.xls': 'application/vnd.ms-excel',
  '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.gif': 'image/gif',
  // 添加其他文件类型映射
};

// 左侧菜单
getFileList = async () => {
  this.setState({ spinning: true }); // 开始加载
  const { formData } = this.state;
  let menuList = [
    { title: '安排表', id: '安排表' },
  ];
  let list = formData.pictureId || []; // 确保 list 是数组
  for (let i = 0; i < list.length; i++) {
    try {
      const fileId = list[i];
      const res = await FileService.queryFileId(fileId); // 查询文件信息
      if (res.data.code === 200) {
        let obj = {
          ...res.data.data,
          title: res.data.data.fileName,
          id: res.data.data.fileId + '',
        };

        // 获取文件扩展名，确保 fileFormat 存在且是字符串
        let fileExtension = obj.fileFormat || obj.fileName.split('.').pop().toLowerCase();

        // 根据文件扩展名获取 MIME 类型
        const mimeType = Details.mimeTypeMap[`.${fileExtension}`] || 'application/octet-stream';

        // 创建 URL 对象
        const downloadRes = await FileService.downloadFile(fileId);
        obj.tomcatPath = window.URL.createObjectURL(new Blob([downloadRes.data], { type: mimeType }));
        console.log(`type`, mimeType);

        // 将对象添加到 menuList
        menuList.push(obj);
      }
    } catch (error) {
      console.error(`Error processing file ${list[i]}:`, error);
    }
  }

  // 更新状态
  this.setState({ menuList, spinning: false });
};
  nextBatchNo = async () => {
    const { formData } = this.state;
    let batchNoOld = this.state.batchNoOld;
    let batchNoNew = [];
    let searchItem = {
      pageNum: 1,
      pageSize: 9999,
    }
    searchItem.batchNo = formData.batchNo;
    await SpecialMachineService.findSpecialProvision(searchItem).then(res => {
      this.setState({ loading: false })
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      let dataSource = res.data.data.data;
      if (!dataSource || dataSource.length <= batchNoOld.length) {
        openModalMessage('warning', '无其他批号可查看！');
        return;
      }
      if (dataSource && dataSource.length > batchNoOld.length) {
        for (var item of dataSource) {
          let isExist = false
          for (var ii of batchNoOld) {
            if (ii.specialProvisionId == item.specialProvisionId) {
              isExist = true
              break
            }
          }
          if (!isExist) {
            batchNoNew.push(item);
          }
        }
      }
    })
    if (batchNoNew.length) {
      this.setState({ formData: batchNoNew[0] }, () => {
        batchNoOld.push(batchNoNew[0]);
        this.setState({ batchNoOld })
        this.getFileList()
      })
    }
  }
  // 上一条
  handlePre = () => {
    const { current, menuList } = this.state
    for (let i in menuList) {
      if (current == menuList[i].id) {
        if (i == 1) {
          openModalMessage('warning', '已是第一条数据！');
        } else {
          this.setState({ current: menuList[i - 1].id })
        }
      }
    }
  }
  // 下一条
  handleNext = () => {
    const { current, menuList } = this.state
    for (let i in menuList) {
      if (current == menuList[i].id) {
        if (i == menuList.length - 1) {
          openModalMessage('warning', '已是最后一条数据！');
        } else {
          this.setState({ current: menuList[Number(i) + 1].id })
        }
      }
    }
  }
  downLoadImage = async () => {
    const { current, menuList } = this.state;
    for (var item of menuList) {
      if (item.id === current) {
        // window.open(item.tomcatPath)
        await FileService.downloadFile(item.id).then(res => {
          //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
          let url = window.URL.createObjectURL(new Blob([res.data], { type: res.data.type }))
          // 创建A标签
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          // 设置的下载文件文件名
          const fileName = decodeURI(item.fileName + '.' + item.fileFormat);
          // 触发点击方法
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
        })
      }
    }

  }
  // 打印安排表
  printSchedule = () => {
    var printInnerHTML = window.document.getElementById('schedule').innerHTML;
    window.document.body.innerHTML = printInnerHTML
    window.print();
    window.location.reload();
  }
  // 单打印
  printOne = () => {
    const { printArr, current } = this.state
    if (printArr[0].fileFormat == 'pdf') {
      openModalMessage('warning', '暂不支持 PDF 文件打印，如需打印请点击文件顶部打印按钮！');
      return
    }
    var printInnerHTML = window.document.getElementById('billDetails_all_' + current).innerHTML;
    window.document.body.innerHTML = printInnerHTML
    var printImg = window.document.getElementsByClassName('printImg');
    var loading_img = false;
    if (printImg[0].offsetHeight === 0) {
      loading_img = false;
      return;
    } else {
      loading_img = true
    }
    if (loading_img) {
      clearTimeout(t_img);
      window.print();
      window.location.reload();
    } else {
      var t_img = setTimeout(() => {
        this.printOne()
      }, 500);
    }
  }
  // 打印全部
  printAll = () => {
    const { menuList, current } = this.state
    let printArr = []
    for (let item of menuList) {
      if (item.fileFormat && item.fileFormat != 'pdf') {
        printArr.push(item)
      } else if (item.fileFormat == 'pdf') {
        openModalMessage('warning', '暂不支持 PDF 文件批量打印');
      }
    }
    this.setState({ printArr }, () => {
      var printInnerHTML = window.document.getElementById('billDetails_all_' + current).innerHTML;
      window.document.body.innerHTML = printInnerHTML
      var printImg = window.document.getElementsByClassName('printImg');
      var loading_img = false;
      if (printImg[0].offsetHeight === 0) {
        loading_img = false;
        return;
      } else {
        loading_img = true
      }
      if (loading_img) {
        clearTimeout(t_img);
        window.print();
        window.location.reload();
      } else {
        var t_img = setTimeout(() => {
          this.printAll()
        }, 500);
      }
    })


  }

  render() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { menuList, formData, spinning, printArr, current } = this.state;
    const borderStyle = '1px solid #000'
    const paddingStyle = 5
    const divStyle = { minHeight: 40, padding: '9px 0', textAlign: 'justify' }
    const spanStyle = { display: 'inline-block', width: '100%' }
    return (
      <Spin spinning={spinning}>
        <div style={{ width: '100%', background: '#fff' }}>
          <div style={{ padding: '0 50px' }}>
            <div style={{ padding: '24px 0', background: '#fff', display: 'flex', width: '70%' }}>
              <div width={280} style={{ background: '#fff', minHeight: 480, padding: '0 10px' }}>
                <Menu
                  mode="inline"
                  defaultSelectedKeys={['安排表']}
                  style={{ height: '100%' }}
                  onClick={this.handleClick}
                  selectedKeys={[current]}
                >
                  {
                    menuList && menuList.map((item, index) => <Menu.Item key={item.id}>{item.title}</Menu.Item>)
                  }
                </Menu>
              </div>
              <div>
                {
                  menuList && menuList.map((item, index) =>
                    <div key={item.id + '_' + index} style={{ display: current === item.id ? 'block' : 'none' }}>
                      {
                        index === 0 && <div style={{ fontSize: '22px', fontFamily: 'Source Han Sans CN-Bold, Source Han Sans CN', fontWeight: 'bold', color: '#0E1F33', textAlign: 'center', padding: '15px 0px', borderBottom: '2px solid #D4D7D9' }}>
                          非标装置机（无合同评审部分）生产安排表
                        </div>
                      }

                      {index === 0 ?
                        <DetailsForm formData={formData} ref={node => this.DetailsForm = node} />
                        :
                        <div>
                          <iframe
                            src={item.tomcatPath}
                            height={600} width={800}
                            onClick={() => this.setState({ pictureVisible: true, pictureSrc: item.tomcatPath })}
                            frameBorder="0"
                            allowFullScreen
                          />
                        </div>
                      }
                    </div>)
                }
              </div>
              <div width={280} style={{ display: current == '安排表' ? 'none' : 'flex', flexDirection: 'column', justifyContent: 'center', }}>
                <div onClick={this.handlePre}>
                  {/* 上一条 */}<Icon type="up-circle" style={{ fontSize: '30px', color: '#999' }} />
                </div>
                <div>&nbsp;</div>
                <div onClick={this.handleNext}>
                  {/* 下一条 */}<Icon type="down-circle" style={{ fontSize: '30px', color: '#999' }} />
                </div>
              </div>
            </div>
            <div style={{ textAlign: 'right', width: '25%' }}>
              <Button type='primary' icon='save' style={{ marginRight: 5, display: current !== '安排表' ? 'inline-block' : 'none' }} onClick={this.downLoadImage} >保存到本地</Button>
              <Button type='primary' icon='arrow-right' style={{ marginRight: 5, display: current === '安排表' ? 'inline-block' : 'none' }} onClick={this.nextBatchNo} >下一个批号</Button>
              <Button type='primary' icon='printer' style={{ marginRight: 5, display: current === '安排表' ? 'inline-block' : 'none' }} onClick={this.printSchedule}>打印</Button>
              <Button type='primary' icon='printer' style={{ marginRight: 5, display: current !== '安排表' ? 'inline-block' : 'none' }} onClick={this.printOne} >单打印</Button>
              <Button type='primary' icon='printer' style={{ display: current !== '安排表' ? 'inline-block' : 'none' }} onClick={this.printAll}>打印全部</Button>
            </div>
          </div>
          {/* 打印图片 */}
          <div id={"billDetails_all_" + current} style={{ display: 'none' }}>
            {
              printArr && printArr.map((item, index) => {
                return item.fileFormat == 'pdf' ?
                  // <iframe src={item.tomcatPath} height={400} width={'100%'} className="imgPrint"></iframe>
                  null
                  :
                  <div>
                    <img key={index} alt='logo' className={'printImg'} src={item.tomcatPath} />
                  </div>
              })
            }
          </div>
          {/* 打印安排表 */}
          <div id='schedule' style={{ display: 'none' }}>
            {/* alignItems: 'center' */}
            <div style={{ width: '100%', height: '100%', display: 'flex', justifyContent: 'center', padding: 50 }}>
              <table cellPadding={0} cellSpacing={0} width={780}>
                <tbody>
                  <tr>
                    <td width={90} ></td>
                    <td width={105} ></td>
                    <td width={195}></td>
                    <td width={90} ></td>
                    <td width={105} ></td>
                    <td width={195}></td>
                  </tr>
                  <tr style={{ height: 80, border: 0, fontSize: 20, fontWeight: 'bold', textAlign: 'center' }}>
                    <td colSpan={6}>标准选配项生产安排表</td>
                  </tr>
                  <tr style={{ border: borderStyle }}>
                    <td style={{ padding: paddingStyle }}><div style={divStyle}>顺&nbsp;&nbsp;序&nbsp;&nbsp;号：</div></td>
                    <td style={{ borderRight: borderStyle, padding: paddingStyle }} colSpan={2}><div style={divStyle}>{formData.orderNo}</div></td>
                    <td style={{ padding: paddingStyle }}>出机日期：</td>
                    <td style={{ padding: paddingStyle }} colSpan={2}><div style={divStyle}>{formData.firstOutputTime}</div></td>
                  </tr>
                  <tr style={{ minHeight: 40, border: borderStyle }}>
                    <td style={{ padding: paddingStyle }}>机&emsp;&nbsp;&emsp;型：</td>
                    <td style={{ borderRight: borderStyle, padding: paddingStyle }} colSpan={2}><div style={divStyle}>{formData.model}</div></td>
                    <td style={{ padding: paddingStyle }}>合同编号：</td>
                    <td style={{ padding: paddingStyle }} colSpan={2}><div style={divStyle}>{formData.contractNo}</div></td>
                  </tr>
                  <tr style={{ minHeight: 40, border: borderStyle }}>
                    <td style={{ padding: paddingStyle }}>批号/台号：</td>
                    <td style={{ borderRight: borderStyle, padding: paddingStyle }} colSpan={2}><div style={divStyle}>{formData.batchNo}</div></td>
                    <td style={{ padding: paddingStyle }}>加工性质：</td>
                    <td style={{ padding: paddingStyle }} colSpan={2}><div style={divStyle}></div></td>
                  </tr>
                  <tr style={{ minHeight: 40, border: borderStyle }}>
                    <td style={{ padding: paddingStyle }}>客户名称：</td>
                    <td style={{ padding: paddingStyle }} colSpan={5}><div style={divStyle}>{formData.customerName}</div></td>
                  </tr>
                  <tr style={{ minHeight: 40, border: borderStyle }}>
                    <td style={{ padding: paddingStyle }}>特供内容：</td>
                    <td style={{ padding: paddingStyle }} colSpan={5}><div style={divStyle}>{formData.specialContent}</div></td>
                  </tr>
                  <tr style={{ minHeight: 100, border: borderStyle }}>
                    <td style={{ borderRight: borderStyle, padding: paddingStyle, textAlign: 'center' }}>备注</td>
                    <td style={{ padding: paddingStyle }} colSpan={5}><div style={{ minHeight: 100, padding: '9px 0' }}>{formData.remarks}</div></td>
                  </tr>
                  <tr style={{ minHeight: 40, border: borderStyle }}>
                    <td style={{ padding: paddingStyle }}><div style={divStyle}>编制：</div></td>
                    <td style={{ padding: paddingStyle }}></td>
                    <td style={{ borderRight: borderStyle, padding: paddingStyle }}>日期：</td>
                    <td style={{ padding: paddingStyle }}>审批：</td>
                    <td style={{ padding: paddingStyle }}></td>
                    <td style={{ padding: paddingStyle }}>日期：</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </Spin>
    );
  }
}

export default Form.create()(Details);
